// ==UserScript==
// @name         快麦通保存辅助终极优化版
// @namespace    http://tampermonkey.net/
// @version      2025-07-17
// @description  优化点击延迟顺序，确保操作可靠性
// @author       You
// @match        https://scm4.superboss.cc/supplier/prod/center?isHideMenu=1&hasCookie=true
// @icon         https://www.google.com/s2/favicons?sz=64&domain=superboss.cc
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    const DELAY_CONFIG = {
        AFTER_CLICK: 1000,          // 每次点击后的基础等待时间
        AFTER_EDIT_OPEN: 1500,      // 编辑框打开后的额外等待
        AFTER_TAB_SWITCH: 1500,     // 标签页切换后的等待
        AFTER_SAVE_ACTION: 2000,    // 保存操作后的等待
        BETWEEN_ITEMS: 1000,        // 两个项目之间的间隔
        NEXT_PAGE_DELAY: 3000,      // 翻页后的等待
        ELEMENT_WAIT_TIMEOUT: 5000  // 元素等待超时
    };

    // 自定义元素查找函数
    function findElementByText(selector, text) {
        const elements = document.querySelectorAll(selector);
        return Array.from(elements).find(el =>
            el.textContent.trim().includes(text)
        );
    }

    // UI设置
    function initUI() {
        const style = document.createElement('style');
        style.textContent = `
            #kmt-helper-btn {
                position: fixed;
                top: 20px;
                right: 20px;
                width: 50px;
                height: 50px;
                border-radius: 50%;
                background-color: #409EFF;
                color: white;
                border: none;
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
                cursor: pointer;
                font-size: 14px;
                z-index: 9999;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: all 0.3s;
            }
            #kmt-helper-btn:hover { background-color: #66b1ff; transform: scale(1.1); }
            #kmt-helper-btn:active { transform: scale(0.95); }
            #kmt-helper-btn.disabled { background-color: #cccccc; cursor: not-allowed; }
            #kmt-helper-status {
                position: fixed;
                top: 80px;
                right: 20px;
                background: white;
                padding: 5px 10px;
                border-radius: 4px;
                box-shadow: 0 2px 5px rgba(0,0,0,0.2);
                z-index: 9998;
            }
        `;
        document.head.appendChild(style);

        const btn = document.createElement('button');
        btn.id = 'kmt-helper-btn';
        btn.title = '快麦通保存辅助';
        btn.textContent = '启动';
        document.body.appendChild(btn);

        const statusDiv = document.createElement('div');
        statusDiv.id = 'kmt-helper-status';
        statusDiv.textContent = '状态: 就绪';
        document.body.appendChild(statusDiv);

        return { btn, statusDiv };
    }

    // 核心功能
    class KmtHelper {
        constructor() {
            this.isRunning = false;
            this.currentIndex = 0;
            this.editButtons = [];
            this.ui = initUI();
            this.bindEvents();
        }

        bindEvents() {
            this.ui.btn.addEventListener('click', () => {
                if (this.isRunning) {
                    this.stop();
                } else {
                    this.start();
                }
            });
        }

        async start() {
            this.isRunning = true;
            this.ui.btn.textContent = '停止';
            this.ui.btn.classList.add('disabled');
            this.updateStatus('正在启动...');

            await this.collectEditButtons();
            if (this.editButtons.length === 0) {
                this.updateStatus('未找到编辑按钮');
                this.stop();
                return;
            }

            this.currentIndex = 0;
            this.processNext();
        }

        stop() {
            this.isRunning = false;
            this.ui.btn.textContent = '启动';
            this.ui.btn.classList.remove('disabled');
            this.updateStatus('已停止');
        }

        updateStatus(text) {
            this.ui.statusDiv.textContent = `状态: ${text}`;
            console.log(text);
        }

        async collectEditButtons() {
            this.updateStatus('正在收集编辑按钮...');
            const buttons = Array.from(document.querySelectorAll('button.el-button'));
            this.editButtons = buttons.filter(button => {
                const span = button.querySelector('span');
                return span && span.textContent.trim().includes('编辑');
            });
            this.updateStatus(`找到 ${this.editButtons.length} 个编辑按钮`);
        }

        async processNext() {
            if (!this.isRunning || this.currentIndex >= this.editButtons.length) {
                this.updateStatus('正在检查下一页...');
                await this.handleNextPage();
                return;
            }

            const success = await this.processCurrentItem();
            if (success) {
                this.currentIndex++;
                setTimeout(() => this.processNext(), DELAY_CONFIG.BETWEEN_ITEMS);
            } else {
                this.stop();
            }
        }

        async processCurrentItem() {
            const editButton = this.editButtons[this.currentIndex];
            this.updateStatus(`正在处理第 ${this.currentIndex + 1}/${this.editButtons.length} 项`);

            try {
                // 1. 点击编辑按钮
                await this.safeClick(editButton, '编辑按钮');
                await this.delay(DELAY_CONFIG.AFTER_EDIT_OPEN);

                // 2. 第一次保存
                const saveBtn1 = await this.waitForSaveButton();
                await this.safeClick(saveBtn1, '第一次保存');
                await this.delay(DELAY_CONFIG.AFTER_SAVE_ACTION);

                // 3. 拼多多标签
                const pddTab = await this.waitForPddTab();
                await this.safeClick(pddTab, '拼多多标签');
                await this.delay(DELAY_CONFIG.AFTER_TAB_SWITCH);

                // 4. 第二次保存
                const saveBtn2 = await this.waitForSaveButton();
                await this.safeClick(saveBtn2, '第二次保存');
                await this.delay(DELAY_CONFIG.AFTER_SAVE_ACTION);

                // 5. 关闭编辑框
                const closeBtn = await this.waitForCloseButton();
                await this.safeClick(closeBtn, '关闭按钮');
                await this.delay(DELAY_CONFIG.AFTER_CLICK);

                return true;
            } catch (error) {
                this.updateStatus(`处理失败: ${error.message}`);
                return false;
            }
        }

        async safeClick(element, actionName) {
            if (!this.isRunning) throw new Error('操作已停止');
            if (!element || element.disabled) throw new Error(`未找到或不可点击: ${actionName}`);

            element.click();
            this.updateStatus(`已点击: ${actionName}`);
            await this.delay(DELAY_CONFIG.AFTER_CLICK);
        }

        async delay(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
        }

        async waitForSaveButton() {
            return this.waitForElement(() => {
                const buttons = document.querySelectorAll('div.left > button.el-button--primary');
                for (const btn of buttons) {
                    const span = btn.querySelector('span');
                    if (span && span.textContent.trim().includes('保 存')) {
                        return btn;
                    }
                }
                return null;
            }, '保存按钮');
        }

        async waitForPddTab() {
            return this.waitForElement(() =>
                findElementByText('div.el-tabs__item', '拼多多资料'),
                '拼多多标签'
            );
        }

        async waitForCloseButton() {
            return this.waitForElement(() =>
                document.querySelector('button[aria-label="close 商品编辑"], button.el-dialog__headerbtn'),
                '关闭按钮'
            );
        }

        async handleNextPage() {
            try {
                const nextPageBtn = document.querySelector('button.btn-next:not(:disabled)');
                if (nextPageBtn) {
                    await this.safeClick(nextPageBtn, '下一页按钮');
                    this.updateStatus('正在加载下一页...');
                    await this.delay(DELAY_CONFIG.NEXT_PAGE_DELAY);

                    if (this.isRunning) {
                        await this.start();
                    }
                } else {
                    this.updateStatus('已完成所有页面');
                    this.stop();
                }
            } catch (error) {
                this.updateStatus(`翻页失败: ${error.message}`);
                this.stop();
            }
        }

        async waitForElement(finder, elementName, timeout = DELAY_CONFIG.ELEMENT_WAIT_TIMEOUT) {
            const start = Date.now();
            while (Date.now() - start < timeout) {
                const el = finder();
                if (el && !el.disabled) return el;
                await this.delay(200);
            }
            throw new Error(`等待元素超时: ${elementName}`);
        }
    }

    // 启动助手
    new KmtHelper();
})();